import sys
from PyQt5.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
from PyQt5.QtGui import QPixmap
from PyQt5.QtCore import Qt, pyqtSignal, QUrl
from PyQt5.QtNetwork import QNetworkAccessManager, QNetworkRequest, QNetworkReply

# 假设你有一个本地的默认图片路径
default_image_path = "resource/img.png"

class NetworkImageView(QLabel):
    # 定义一个信号，用于通知图片加载完成
    imageLoadedSignal = pyqtSignal(QPixmap)

    def __init__(self, url=None, parent=None):
        super().__init__(parent)
        self.url = url
        self.default_pixmap = QPixmap(default_image_path)
        self.setFixedSize(400, 400)  # 设置初始大小为200*200
        self.setDefaultPixmap()
        self.initUI()

    def setUrl(self, url):
        self.url = url

    def setDefaultPixmap(self):
        if not self.default_pixmap.isNull():
            self.setPixmap(self.default_pixmap.scaled(400, 400, Qt.KeepAspectRatio, Qt.SmoothTransformation))

    def initUI(self):
        # 创建网络访问管理器
        self.manager = QNetworkAccessManager(self)
        self.manager.finished.connect(self.handle_network_response)

        # 发起HTTP GET请求获取图片数据
        self.request = QNetworkRequest(QUrl(self.url))
        self.manager.get(self.request)

    def handle_network_response(self, reply: QNetworkReply):
        if reply.error() == QNetworkReply.NoError:
            # 获取图片数据并转化为QPixmap
            image_data = reply.readAll()
            pixmap = QPixmap()
            pixmap.loadFromData(image_data)

            # 设置QLabel的pixmap
            if pixmap.isNull():
                print("Failed to load the image")
            else:
                pixmap = pixmap.scaled(400, 400, Qt.KeepAspectRatio, Qt.SmoothTransformation)
                self.setPixmap(pixmap)
                # 发射图片加载完成信号，并携带已加载的QPixmap
                self.imageLoadedSignal.emit(pixmap)

        else:
            print(f"Error loading image: {reply.errorString()}")

if __name__ == "__main__":
    app = QApplication(sys.argv)

    # 创建窗口及布局
    window = QWidget()
    layout = QVBoxLayout(window)

    # 加载网络图片到QLabel
    imageUrl = "https://p6-pc-sign.douyinpic.com/image-cut-tos-priv/273ce8f0cb888bfb96cc4b319ee21c34~tplv-dy-resize-origshort-autoq-75:330.jpeg?x-expires=2029298400&x-signature=0MG9PDb8A1WBKnmbl2Yv7mwbWw8%3D&from=3213915784&s=PackSourceEnum_AWEME_DETAIL&se=false&sc=cover&biz_tag=pcweb_cover&l=2024042414023477A7C294EF762278E132"
    network_label = NetworkImageView(imageUrl)
    layout.addWidget(network_label)

    window.show()

    sys.exit(app.exec_())